import { Component, OnInit, OnDestroy } from '@angular/core';
import {
  FormBuilder,
  FormGroup,
  Validators
} from '@angular/forms';

import { AccountService } from '../../services/account.service';
import { Subscription } from 'rxjs/Subscription';

@Component({
  selector: 'app-signin',
  templateUrl: './signin.component.html',
  styleUrls: ['./signin.component.less']
})

export class SigninComponent implements OnInit, OnDestroy {

  constructor(private fb: FormBuilder, private accountService: AccountService) { }

  validateForm: FormGroup;
  observer: Subscription;
  error = '';
  count = 0;
  type = 0;
  interval$: any;
  loading = false;

  submitForm(): void {
    this.error = '';
    if (this.type === 0) {
      this.userName.markAsDirty();
      this.userName.updateValueAndValidity();
      this.password.markAsDirty();
      this.password.updateValueAndValidity();
      if (this.userName.invalid || this.password.invalid) { return; }
    } else {
      this.mobile.markAsDirty();
      this.mobile.updateValueAndValidity();
      this.captcha.markAsDirty();
      this.captcha.updateValueAndValidity();
      if (this.mobile.invalid || this.captcha.invalid) { return; }
    }
    // mock http
    this.loading = true;
    // for (const i in this.validateForm.controls) {
    //   this.validateForm.controls[i].markAsDirty();
    //   this.validateForm.controls[i].updateValueAndValidity();
    // }
    this.accountService.signin(this.validateForm.value.userName, this.validateForm.value.password);
  }

  ngOnInit(): void {

    this.validateForm = this.fb.group({
      userName: [null, [Validators.required, Validators.minLength(6)]],
      password: [null, [Validators.required, Validators.minLength(6)]],
      mobile: [null, [Validators.required, Validators.pattern(/^1\d{10}$/)]],
      captcha: [null, [Validators.required]],
      remember: [true]
    });

    this.observer = this.accountService.subjectSignin.subscribe({
      next: (data) => {
        this.error = data;
        this.loading = false;
      }
    });
  }

  getCaptcha() {
    this.count = 59;
    this.interval$ = setInterval(() => {
      this.count -= 1;
      if (this.count <= 0) {
        clearInterval(this.interval$);
      }
    }, 1000);
  }

  switch(ret: any) {
    this.type = ret.index;
  }

  ngOnDestroy() {
    this.observer.unsubscribe();
    if (this.interval$) { clearInterval(this.interval$); }
  }

  get userName() { return this.validateForm.controls.userName; }
  get password() { return this.validateForm.controls.password; }
  get mobile() { return this.validateForm.controls.mobile; }
  get captcha() { return this.validateForm.controls.captcha; }

}
